#!/bin/sh

set -eu
dotenv_env_name_file=''
onexit() {
  if [ -e "$dotenv_env_name_file" ]; then
    rm "$dotenv_env_name_file"
  fi
}
trap onexit EXIT

# shdotenv() { src/shdotenv "$@"; }

load_dotenv() {
  [ "$dotenv_env_name_file" ] || dotenv_env_name_file=$(mktemp)
  env=$(shdotenv --env "$1")
  eval "$env"
  shdotenv --env "$1" --keyonly >> "$dotenv_env_name_file"
  dotenv_loaded=1
}

dotenv_loaded='' is_env_file_flag='' stop_parse_arguments=''
for i in "$@"; do
  if [ "$is_env_file_flag" ] && is_env_file_flag=''; then
    load_dotenv "$i"
    shift && continue
  fi
  [ "$stop_parse_arguments" ] && set -- "$@" "$i" && shift && continue
  [ "$i" = "--env-file" ] && is_env_file_flag=1 && shift && continue
  [ "$i" = "--" ] && stop_parse_arguments=1
  set -- "$@" "$i" && shift
done
[ "$dotenv_loaded" ] || load_dotenv ".env"

stop_parse_arguments=''
for i in "$@"; do
  [ "$stop_parse_arguments" ] && set -- "$@" "$i" && shift && continue
  case $i in (-*) set -- "$@" "$i"; shift; continue; esac
  stop_parse_arguments=1
  set -- "$@" "$i" --env-file "$dotenv_env_name_file" && shift
done
docker "$@"
